//
//  LPTpatientsDetailViewController.m
//  LPTClient
//
//  Created by mac on 2018/12/8.
//  Copyright © 2018年 zhaodd. All rights reserved.
//

#import "LPTpatientsDetailViewController.h"
#import "LPTPatientsFooterView.h"
#import "LPTPatientsDetailTableViewCell.h"
#import "LPTPatientsPicTableViewCell.h"
#import "LPTDiagnosisDetailViewController.h"

@interface LPTpatientsDetailViewController ()<UITableViewDataSource,UITableViewDelegate,LPTPatientsFooterViewDelegate>

@property (nonatomic,copy)NSDictionary *dic;

@end

@implementation LPTpatientsDetailViewController

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"pushToDiagnosisDetailVC"]) {
        
        LPTDiagnosisDetailViewController *diaVC = segue.destinationViewController;
        diaVC.visit_id = self.dic[@"id"];
    }
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initSubViews];
    
    if (self.type == kDaizhenduanType) {
        [self getDaizhenduanDetailData];
    }else{    
        [self getZhenduanDetailData];
    }
}

-(void)initSubViews
{
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44;
    
    if (self.type == kWenzhenType) {
        
        self.tableView.tableFooterView = [UIView new];
    }
}

//待诊断
-(void)getDaizhenduanDetailData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *api = [NSString stringWithFormat:@"/api/diagnosis_form/%@",self.zhenduanid];
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:api withBody:@{@"id":self.zhenduanid}];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        self.dic = data[@"visit"];
        [self.dataSource removeAllObjects];
        [self.dataSource addObject:self.dic[@"archive"]];
        [self.dataSource addObject:self.dic[@"complaint"][@"signs"]];
        [self.dataSource addObject:self.dic[@"complaint"]];
        
//        if (self.dic[@"complaint"][@"images"] && [self.dic[@"complaint"][@"images"] isKindOfClass:[NSNull class]]) {
        
            [self.dataSource addObject:self.dic[@"complaint"][@"images"]];
//        }
        
        LPTPatientsFooterView *footerView = [[LPTPatientsFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
        footerView.delegate = self;
        self.tableView.tableFooterView = footerView;
        
        [self.tableView reloadData];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
    }];
}

//诊断
-(void)getZhenduanDetailData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *api = [NSString stringWithFormat:@"/api/text_visit_detail/%@",self.zhenduanid];
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:api withBody:@{@"id":self.zhenduanid}];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        self.dic = data[@"visit"];
        [self.dataSource removeAllObjects];
        [self.dataSource addObject:self.dic[@"archive"]];
        [self.dataSource addObject:self.dic[@"complaint"][@"signs"]];
        [self.dataSource addObject:self.dic[@"complaint"]];
        
//        if (self.dic[@"complaint"][@"images"] && [self.dic[@"complaint"][@"images"] isKindOfClass:[NSNull class]]) {
        
            [self.dataSource addObject:self.dic[@"complaint"][@"images"]];
//        }
        
        if ([self getZhenduanDic]) {
            
            [self.dataSource addObject:[self getZhenduanDic]];
        }
        
        if (![self.dic[@"order"] isKindOfClass:[NSNull class]] && self.dic[@"order"] != nil) {
            
            [self.dataSource addObject:self.dic[@"order"]];
        }
        [self.tableView reloadData];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
    }];
}

-(NSDictionary *)getZhenduanDic
{
    NSDictionary *dic = @{@"诊断结果":self.dic[@"diagnosis"],@"医嘱":self.dic[@"advice"],@"复诊时间":self.dic[@"revisit_date"],@"是否开处方":[self.dic[@"status"] integerValue] == 2?@"已开":@"未开"};
    return dic;
}

#pragma mark - UITableViewDataSource & Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self getRowCountWithType:self.type withSection:section];
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self getSectionTitleWithType:self.type withIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [self getSectionTitleWithType:self.type withIndexPath:indexPath];
    
    if ([title isEqualToString:@"症状图片"]){
        return 140;
    }else if ([title isEqualToString:@"处方"]){
        
        if ([[self getTitleWithType:self.type withIndexPath:indexPath] isEqualToString:@"成分"]) {
            
            NSString *chufangStr = [self getContentWithType:self.type withIndexPath:indexPath];
            CGRect rect = [chufangStr boundingRectWithSize:CGSizeMake(kScreenWidth - 104, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]} context:nil];
            CGFloat height = rect.size.height;
            
            if (height < 44) {
                return 44;
            }
            
            return height + 30;
        }
    }
    
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [self getSectionTitleWithType:self.type withIndexPath:indexPath];
    
    if ([title isEqualToString:@"症状图片"]) {
        
        LPTPatientsPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTPatientsPicTableViewCell" forIndexPath:indexPath];
        [cell refreshWithArray:self.dataSource[indexPath.section]];
        return cell;
        
    }else{
        
        LPTPatientsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTPatientsDetailTableViewCell" forIndexPath:indexPath];
        cell.titleLab.text = [self getTitleWithType:self.type withIndexPath:indexPath];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",[self getContentWithType:self.type withIndexPath:indexPath]];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *title = [self getSectionTitleWithType:self.type withIndexPath:indexPath];
    NSMutableArray *imgarray = [NSMutableArray array];
    if ([title isEqualToString:@"症状图片"]) {
        
        NSArray *array = self.dataSource[indexPath.section];
        for (NSDictionary *dic in array) {
            
            NSString *urlString = [NSString stringWithFormat:@"%@/%@",BASE_URL,dic[@"url"]];
            [imgarray addObject:urlString];
        }
    }
    
    if (imgarray.count) {
        [self showBrowserWithArray:imgarray];
    }
}

#pragma mark - LPTPatientsFooterViewDelegate
-(void)patientsFooterViewDidClickSaveBtn
{
    [self performSegueWithIdentifier:@"pushToDiagnosisDetailVC" sender:nil];
}

#pragma mark ------PrimTableViewData
-(NSInteger)getRowCountWithType:(PatientsDetailType)type withSection:(NSInteger)section
{
    if (type == kDaizhenduanType) {
        
        if (section == 0) {
            return 8;
        }else if (section == 1){
            NSDictionary *dic = self.dataSource[section];
            NSArray <NSDictionary *>*array = (NSArray *)dic;
            return array.count;
        }else if (section == 2){
            return 2;
        }else{
            return 1;
        }
    }else{
        
        if (section == 0) {
            return 8;
        }else if (section == 1){
            return 9;
        }else if (section == 2){
            return 2;
        }else if (section == 3){
            return 1;
        }else if (section == 4){
            return 4;
        }else{
            return 5;
        }
    }
    
}

-(NSString *)getSectionTitleWithType:(PatientsDetailType)type withIndexPath:(NSIndexPath *)indexPath
{
    if (type == kDaizhenduanType) {
    
            switch (indexPath.section) {
                case 0:
                {
                    return @"健康档案";
                }break;
                case 1:
                {
                    return @"辩证体质";
                }break;
                case 2:
                {
                    return @"症状描述";
                }break;
                case 3:
                {
                    return @"症状图片";
                }break;
                default:{
                    return @"";
                    break;
            }
        }
    }else{
        
        switch (indexPath.section) {
            case 0:
            {
                return @"健康档案";
            }break;
            case 1:
            {
                return @"辩证体质";
            }break;
            case 2:
            {
                return @"症状描述";
            }break;
            case 3:
            {
                return @"症状图片";
            }break;
            case 4:
            {
                return @"诊断";
            }break;
            case 5:
            {
                return @"处方";
            }break;
                
            default:
                return @"";
                break;
        
    }
        
    }
}

//获取标题
-(NSString *)getTitleWithType:(PatientsDetailType)type withIndexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case kDaizhenduanType:
        {
        
            //待诊断
            if (indexPath.section == 0) {
                NSArray *titleArray = @[@"姓名",@"关系",@"年龄",@"身高",@"体重",@"过敏史",@"既往病史",@"慢性病史"];
                return titleArray[indexPath.row];
            }else if (indexPath.section == 1){
                
                NSDictionary *dic = self.dataSource[indexPath.section];
                NSArray <NSDictionary *>*array = (NSArray *)dic;
                NSDictionary *subDic = array[indexPath.row];
                return [subDic valueForKey:@"name"];
            }else if (indexPath.section == 2){
                NSArray *titleArray = @[@"疾病",[self.dataSource[2] valueForKey:@"symptom"]];
                return titleArray[indexPath.row];
            }
            
            return @"";
            
        }break;
        case kWenzhenType:
        {
            
            //诊断
            //待诊断
            if (indexPath.section == 0) {
                NSArray *titleArray = @[@"姓名",@"关系",@"年龄",@"身高",@"体重",@"过敏史",@"既往病史",@"慢性病史"];
                return titleArray[indexPath.row];
            }else if (indexPath.section == 1){
                
                NSDictionary *dic = self.dataSource[indexPath.section];
                NSArray <NSDictionary *>*array = (NSArray *)dic;
                NSDictionary *subDic = array[indexPath.row];
                return [subDic valueForKey:@"name"];
                
            }else if (indexPath.section == 2){
                NSArray *titleArray = @[@"疾病",[self.dataSource[2] valueForKey:@"symptom"]];
                return titleArray[indexPath.row];
                
            }else if (indexPath.section == 4){
                
                NSDictionary *dic = self.dataSource[indexPath.section];
                NSString *key = [[dic allKeys] objectAtIndex:indexPath.row];
                return key;
            }else if (indexPath.section == 5){
                NSArray *titleArray = @[@"剂量",@"用法",@"订单",@"总金额",@"成分"];
                return titleArray[indexPath.row];
            }
            
            return @"";
            
        }break;
            
        default:
            break;
    }
}

-(NSString *)getContentWithType:(PatientsDetailType)type withIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataSource[indexPath.section];
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            return dic[@"name"];
            
        }else if (indexPath.row == 1){
            
            return [dic[@"relationship"] integerValue] == 0?@"本人":@"家人";
            
        }else if (indexPath.row == 2){
            
            return dic[@"age"];
        }else if (indexPath.row == 3){
            return dic[@"height"];
        }else if (indexPath.row == 4){
            return dic[@"weight"];
        }else if (indexPath.row == 5){
            return @"";
        }else if (indexPath.row == 6){
            return @"";
        }else if (indexPath.row == 7){
            return @"";
        }
    }else if (indexPath.section == 1){
        
        NSArray <NSDictionary *>*array = (NSArray *)dic;
        NSDictionary *subDic = array[indexPath.row];
        return [subDic valueForKey:@"value"];
        
    }else if (indexPath.section == 2){
        
        if (indexPath.row == 0) {
            
            return dic[@"disease"];
        }else{
            return @"";
        }
        
    }else if (indexPath.section == 3){
        
        return @"";
        
    }else if (indexPath.section == 4){
     
        NSString *key = [[dic allKeys] objectAtIndex:indexPath.row];
        return dic[key];
        
    }else{
        
        if (indexPath.row == 0) {
            return [NSString stringWithFormat:@"%@剂",dic[@"recipe"][@"quantity"]];
        }else if (indexPath.row == 1){
            return @"冲服，每日三次";
        }else if (indexPath.row == 2){
            return [dic[@"status"] integerValue] == 3?@"已下单，待付款":@"已完成";
        }else if (indexPath.row == 3){
            return dic[@"amount"];
        }else{
            
            NSArray *array = dic[@"recipe"][@"detail"];
            
            NSMutableArray *stringArray = [NSMutableArray new];
            for (NSDictionary *subDic in array) {
                
                NSString *subString = [NSString stringWithFormat:@"%@ %@g     %@(元/g)    总计%.2f(元)",subDic[@"name"],subDic[@"weight"],subDic[@"price"],[subDic[@"amount"] doubleValue]/1.0f];
                [stringArray addObject:subString];
            }
            
            NSString *string = [stringArray componentsJoinedByString:@"\n"];
            
            return string;
        }
    }
    
    return @"";
}

#pragma mark - 相册
-(void)showBrowserWithArray:(NSArray *)array
{
    WMPhotoBrowser *browser = [WMPhotoBrowser new];
    browser.dataSource = array.mutableCopy;
    browser.downLoadNeeded = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

@end
